<?php

namespace App\Http\Controllers\Admin;

use App\Enums\RedisKeyEnum;
use App\Services\Tools\SmsService;
use Illuminate\Support\Facades\DB;
use App\Models\MainDB\PayMerchant;
use App\Services\Tools\CreateCheckImg;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

//引用http请求类
use App\Exceptions\BasicException;

//引入框架异常处理类
use Illuminate\Support\Facades\Hash;

//引入hash
use App\Services\Cache\AdminCacheService;

//admin缓存
use App\Services\Tools\JwtService;

//引入JWT服务
use App\Response\Response;
use Illuminate\Support\Facades\Route;

class AdminController extends BaseController
{
    /**
     * @api {post} /admin/login/img 获取拖动验证图片
     * @apiVersion 0.1.0
     * @apiName 获取拖动验证图片
     * @apiGroup 后台设置
     * @apiParam {string} phone 管理员账号
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "y": 38,//被滑动图高度
     * "img": {
     * "big": "temp/checkimg/15279831247B.jpg",//底图
     * "small": "temp/checkimg/15279831247S.jpg"//被滑动的图前面拼接上接口域名
     * }
     * }
     * }
     * @apiError 20001 管理员账号不存在
     * @apiError 20002 管理员已经被封禁
     * @apiError 20003 登录密码错误
     */
    public function getDragImg(Request $request)
    {

        $param = $request->only(['phone']);
        $va = app('validator')->make($param, [
            'phone' => 'required|regex:/^1[345789][0-9]{9}$/',
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $admin = app('repo_admin')->admin_detail($param['phone'], 'phone_number', true, true);
        if (empty($admin)) {
            throw new BasicException(20001);
        }
        //是否禁用
        if ($admin->disabled != 1) {
            throw new BasicException(20002);
        }

        $checkImg = new CreateCheckImg($param['phone']);
        $imgData = $checkImg->create();
        $rdata = [
            'y'   => $imgData['y'],
            'img' => $imgData['img'],
        ];

        return Response::sendData($rdata, '发送成功');
    }

    /**
     * @api {post} /admin/login/valiimg 验证通过滑动验证
     * @apiVersion 0.1.0
     * @apiName 获取短信验证码
     * @apiGroup 后台设置
     * @apiParam {string} phone 管理员账号
     * @apiParam {int} x 向右边移动的横坐标像素点数  （误差在5个像素点之内）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": 1
     * }
     * @apiError 10001 请先获取滑动图形验证码
     */
    public function valiImg(Request $request)
    {
        $param = $request->all(['phone', 'x']);
        $messages = [
            'phone.regex' => '手机号不合法',
        ];
        $validator = \Validator::make($param, [
            'phone' => 'required|regex:/^1[345789][0-9]{9}$/',
            'x'     => 'required|integer|min:1',//移动横坐标
        ], $messages);
        $error = $validator->errors()->first();
        if ($error) {
            return Response::sendData($error);
        }
        $checkImg = new CreateCheckImg($param['phone']);
        $checkImg->verify($param['x']);                                                                                                             //验证图片滑动是否正确 错误会直接抛出异常
        app('redis')->setex(sprintf(RedisKeyEnum::ADMIN_CAN_USE_SMS, $param['phone']), 60, 1);                                                      //标记该管理员通过了拖动验证 ，

        return Response::sendData(1, '验证成功，请在一分钟内发送短信验证码');
    }

    /**
     * @api {post} /admin/login/sms 获取短信验证码
     * @apiVersion 0.1.0
     * @apiName 获取短信验证码
     * @apiGroup 后台设置
     * @apiParam {string} phone 管理员账号
     * @apiParam {int} x 向右边移动的横坐标像素点数  （误差在5个像素点之内）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": '发送成功'
     * }
     * @apiError 10010 请先通过拖动图形验证
     */
    public function sendSms(Request $request)
    {
        $param = $request->all(['phone']);
        $messages = [
            'phone.regex' => '手机号不合法',
        ];
        $validator = \Validator::make($param, [
            'phone' => 'required|regex:/^1[345789][0-9]{9}$/',

        ], $messages);
        $error = $validator->errors()->first();
        if ($error) {
            throw new BasicException(10010, $error);
        }

        $isCanSendmsms = app('redis')->get(sprintf(RedisKeyEnum::ADMIN_CAN_USE_SMS, $param['phone']));
        if ($isCanSendmsms != 1) {//没有通过拖动图形验证
//            throw new BasicException(10010, '请先通过拖动图形验证');
        }
        app('redis')->del(sprintf(RedisKeyEnum::ADMIN_CAN_USE_SMS, $param['phone']));
        $sms_code = randCode(app("model_config")->getValue('SMS_CODE_LEN'), 1);
        $send_status = SmsService::send($param['phone'], 11, ['code' => $sms_code], 1);
        if ($send_status) {
            return Response::sendData(1, '发送成功');
        } else {
            throw new BasicException(10010, '发送失败, 请稍后再试');
        }
    }

    /**
     * @api {post} /admin/login/code 短信验证码登录方式
     * @apiVersion 0.1.0
     * @apiName 短信验证码登录方式
     * @apiGroup 后台设置
     * @apiParam {string} phone 管理员账号
     * @apiParam {string} code 短信验证码
     * @apiSuccessExample 成功响应
     *     {
     * "code": 200,
     * "data": {
     * "token(token值)": "h0YWUS9ncRnZU57aPbfexXHxrvOI0vJxUZ5TjW+rDaM=.YWRtaW5faWQ9MSZzY19pZD0xJnBlcm1pc3Npb25fa2V5PUwyMWxiblV2WVdSa0xERXlNdyUzRCUzRCZ0eXBlPTEmZXhwaXJlX3RpbWU9MTU5NTk5MDU5OSZyYW5kb209MTU0MjMyMzQyOA==",
     * "menus(左侧导航菜单信息)": [
     * {
     * "menu_id(菜单编号)": 1,
     * "menu_name(菜单名称)": "首页测试菜单",
     * "menu_key(菜单导航key值)": "/index",
     * "icon(菜单icon)": "",
     * "level(菜单级别)": 1,
     * "children(子菜单)": [
     * {
     * "menu_id": 2,
     * "menu_name": "数据统计",
     * "menu_key": "/index/statics",
     * "icon": "",
     * "level": 2
     * }
     * ]
     * }
     * ],
     * "info(用户信息)": {
     * "admin_name(管理员姓名)": "气泡语音",
     * "avatar(管理员头像)": ""
     * }
     * }
     * }
     * @apiError 20001 管理员账号不存在
     */
    public function smsLogin(Request $request)
    {
        $param = $request->all(['phone', 'code']);
        $messages = [
            'phone.regex' => '手机号不合法',
        ];
        $validator = \Validator::make($param, [
            'phone' => 'required|regex:/^1[345789][0-9]{9}$/',
            'code'  => 'required|string|min:1',     //正则验证
        ], $messages);
        $error = $validator->errors()->first();
        if ($error) {
            return Response::sendData($error);
        }

        if (!SmsService::verify($param['phone'], $param['code'], 11)) {
            throw new BasicException(10010, '短信验证码错误');
        }
        $admin = app('repo_admin')->admin_detail($param['phone'], 'phone_number', true);
        if ($admin) {
            if (isset($admin->admin_role) && $admin->admin_role->role_id > 0) {
                $adminRole = app('model_role')->select('status')->where('role_id', $admin->admin_role->role_id)->first();
                if ($adminRole->status == 2) throw new BasicException(0, '管理员所属角色被禁用');
            }
        } else {
            throw new BasicException(10010, '管理员手机号不存在');
        }

        //生成JWT通信秘钥
        $admin_ifo = [
            'admin_id' => $admin->admin_id,
            'ip'       => ip2long($request->ip()),
        ];
        $token = JwtService::generate_token($admin_ifo);
        //将token缓存到redis，有效期7天
        app('redis')->setex(sprintf(RedisKeyEnum::ADMIN_LOGIN_TOKEN, $admin->admin_id), 7 * 86400, $token);
        //更新登录信息并返回结果(包括菜单数组,权限数组)
        $admin->last_login_ip = $request->ip();
        $admin->last_login_time = time();
        $admin->login_count = $admin->login_count + 1;
        $admin->save();

        $data = [
            'token' => $token,
            'info'  => [
                'admin_name' => $admin->admin_name,
                'avatar'     => !empty($admin->avatar) ? $admin->avatar : env('YUTANG_ADMINI_AVATAR'),
            ],
        ];

        return Response::sendData($data);
    }

    /**
     * @api {post} /valiimg 添加验证图片
     * @apiVersion 0.1.0
     * @apiName 添加验证图片
     * @apiGroup 后台设置
     * @apiParam {String}  img_url        图标地址（必填）
     * @apiSuccessExample 成功响应
     *          {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function addvaliImg(Request $request)
    {
        $param = $request->only(['img_url']);
        $va = app('validator')->make($param,
            [
                'img_url' => 'required|string|max:255',
            ]);
        if ($va->fails()) {
            throw new BasicException(10001, $va->errors()->first());
        }
        $res = app('model_login_matter_img')->insert(['img_url' => $param['img_url']]);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw new BasicException(10001);
        }
    }

    /**
     * @api {put} /valiimg 修改验证图片
     * @apiVersion 0.1.0
     * @apiName 修改验证图片
     * @apiGroup 后台设置
     * @apiParam {int}  id
     * @apiParam {String}  img_url        图标地址（必填）
     * @apiParam {int}  status        图标地址（必填）
     * @apiSuccessExample 成功响应
     *          {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function udpateValiImg(Request $request)
    {
        $param = $request->only(['img_url']);
        $va = app('validator')->make($param,
            [
                'img_url' => 'required|string|max:255',
                'status'  => 'required|in:0,1',
                'id'      => 'required|integer|min:1',
            ]);
        if ($va->fails()) {
            throw new BasicException(10001, $va->errors()->first());
        }
        $res = app('model_login_matter_img')->where('id', $param['id'])->update(['img_url' => $param['img_url'], 'status' => $param['status']]);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw new BasicException(10001);
        }
    }
}
